use std::env;
use std::fs;
use std::io::Write as IoWrite;
use std::io::Write;
#[cfg(test)]
mod filex {
    use std::io::Write;
    use std::path::PathBuf;
    use std::{env, fs, process};

    const BASE_PATH: &str = "src/stdx/iox/";
    #[test]
    fn file_info() {
        let dir_path = env::current_dir().unwrap_or_else(|err| {
            eprintln!("Problem parsing arguments: {err}");
            process::exit(1);
        });
        let new_dir = dir_path.join(BASE_PATH);
        print_file_info(String::from("dir"), new_dir.clone());

        let new_path = new_dir.join("tcpx");
        print_file_info(String::from("yes"), new_path);
        let new_path = new_dir.join("iox2.rs");
        print_file_info(String::from("not"), new_path);
    }

    fn print_file_info(name: String, new_path: PathBuf) {
        println!(
            "extension            {:?}   {:?}",
            name,
            new_path.extension()
        );
        println!(
            "file_name            {:?}   {:?}",
            name,
            new_path.file_name()
        );
        println!(
            "file_stem            {:?}   {:?}",
            name,
            new_path.file_stem()
        );
        println!("is_dir               {:?}   {:?}", name, new_path.is_dir());
        println!("is_file              {:?}   {:?}", name, new_path.is_file());
        println!(
            "is_absolute          {:?}   {:?}",
            name,
            new_path.is_absolute()
        );
        println!(
            "is_relative          {:?}   {:?}",
            name,
            new_path.is_relative()
        );
        println!(
            "is_symlink           {:?}   {:?}",
            name,
            new_path.is_symlink()
        );
        println!("exists               {:?}   {:?}", name, new_path.exists());
        println!(
            "read_dir             {:?}   {:?}",
            name,
            new_path.read_dir()
        );
        println!(
            "read_link            {:?}   {:?}",
            name,
            new_path.read_link()
        );
        println!("to_str               {:?}   {:?}", name, new_path.to_str());
        println!(
            "to_owned             {:?}   {:?}",
            name,
            new_path.to_owned()
        );
        println!(
            "to_path_buf          {:?}   {:?}",
            name,
            new_path.to_path_buf()
        );
        println!(
            "to_string_lossy      {:?}   {:?}",
            name,
            new_path.to_string_lossy()
        );
    }

    #[test]
    fn dir_operate() {
        let dir_path = env::current_dir().expect("TODO: panic message");
        let create_path = dir_path.join(format!("{}{}", BASE_PATH, "temp"));
        println!("{:?}", create_path);
        // temp
        fs::create_dir(&create_path).unwrap();
        fs::create_dir_all(&create_path).unwrap();
        fs::remove_dir(&create_path).unwrap();
        fs::remove_dir_all(&create_path).unwrap()
    }

    #[test]
    fn file_operate() {
        let dir_path = env::current_dir().expect("TODO: panic message");
        let from = dir_path.join(format!("{}{}", BASE_PATH, "iox.rs"));
        fs::create_dir_all(dir_path.join(format!("{}{}", BASE_PATH, "temp"))).unwrap();
        let to = format!("{}{}", BASE_PATH, "temp/io.txt");
        let to = dir_path.join(to);
        fs::copy(from, &to).unwrap();
        fs::rename(to.clone(), to.parent().unwrap().join("new_json.txt")).unwrap();
    }

    #[test]
    fn writer() {
        let dir_path = env::current_dir().expect("TODO: panic message");
        let to = format!("{}{}", BASE_PATH, "temp/io.txt");
        fs::write(to, "asd".as_bytes()).expect("TODO: panic message");
    }

    #[test]
    fn reader() {
        let dir_path = env::current_dir().expect("TODO: panic message");
        let to = format!("{}{}", BASE_PATH, "temp/io.txt");
        if dir_path.is_dir() {
            fs::read_dir(dir_path).unwrap();
        } else {
            fs::read(dir_path).unwrap();
        };
        let mut vec = fs::read(to).unwrap();
        println!("{:?}", vec);

        println!("{:?}", vec.write("aaaaa".as_bytes()));
        println!("{:?}", vec);
    }

    #[test]
    fn read_file() {
        let file = std::fs::OpenOptions::new()
            .truncate(true)
            .read(true)
            .write(true)
            .create(true)
            .open("foo. txt");
        let dir_path = env::current_dir().expect("TODO: panic message");
        println!("{:?}", dir_path);
        let dir = fs::read_dir(&dir_path).expect("Should have been able to read the file");
        println!("{:?}", dir);
        let new_path = dir_path.join("src/iox/tcpx");
        println!("newpath:{:?}", new_path);
        println!("newpath:{:?}", fs::read_to_string(&new_path));
    }
}

// ========== 新增 fsx：文件系统常用示例与中文注释 ==========
// 说明：本文件包含对 std::fs 常见操作的示例（metadata、读/写、复制/重命名、目录遍历等）。
// 所有示例以测试形式出现，便于在本仓库中运行 cargo test 验证（测试会在临时目录下创建并清理文件）。

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;

    #[test]
    fn print_file_info_example() {
        let cwd = env::current_dir().unwrap();
        let base = cwd.join("src/stdx/iox");
        let p = base.join("nonexistent_file_example.txt");

        // 以下方法展示 Path 的常用 API，均不会 panic（除非权限问题）
        println!("extension: {:?}", p.extension());
        println!("file_name: {:?}", p.file_name());
        println!("file_stem: {:?}", p.file_stem());
        println!("exists: {}", p.exists());
        println!("is_dir: {}", p.is_dir());
    }

    #[test]
    fn dir_and_file_ops_example() {
        let cwd = env::current_dir().unwrap();
        let tmp_dir = cwd.join("src/stdx/iox/temp_fs");
        // 创建目录（如果已存在则不会报错）
        fs::create_dir_all(&tmp_dir).unwrap();
        // 创建并写入文件
        let file = tmp_dir.join("t.txt");
        fs::write(&file, b"hello").unwrap();
        // 复制文件
        let copy = tmp_dir.join("t_copy.txt");
        fs::copy(&file, &copy).unwrap();
        // 重命名/移动文件
        let renamed = tmp_dir.join("t_renamed.txt");
        fs::rename(&copy, &renamed).unwrap();
        // 删除文件与目录
        fs::remove_file(&file).unwrap();
        fs::remove_file(&renamed).unwrap();
        fs::remove_dir(&tmp_dir).unwrap();
    }

    #[test]
    fn read_write_examples() {
        let cwd = env::current_dir().unwrap();
        let tmp_dir = cwd.join("src/stdx/iox/temp_fs2");
        fs::create_dir_all(&tmp_dir).unwrap();
        let f = tmp_dir.join("r.txt");
        // write
        {
            let mut file = fs::File::create(&f).unwrap();
            writeln!(file, "line1").unwrap();
            writeln!(file, "line2").unwrap();
        }
        // read_to_string
        let s = fs::read_to_string(&f).unwrap();
        assert!(s.contains("line1"));
        // cleanup
        fs::remove_file(&f).unwrap();
        fs::remove_dir(&tmp_dir).unwrap();
    }
}
